package com.treasure.mall.biz.service.core.user.impl;

import com.treasure.mall.biz.base.AbstractCrudService;
import com.treasure.mall.biz.dto.BaseSaveDTO;
import com.treasure.mall.biz.entity.user.UserFollowPO;
import com.treasure.mall.biz.entity.user.UserPO;
import com.treasure.mall.biz.repository.user.UserFollowRepository;
import com.treasure.mall.biz.repository.user.UserRepository;
import com.treasure.mall.biz.service.core.user.UserFollowService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * @author allan
 * @version 1.0.0
 * @date 2020/7/29
 */
@Service
public class UserFollowServiceImpl extends AbstractCrudService<UserFollowPO, Long> implements UserFollowService {
    private UserFollowRepository followRepository;
    @Autowired
    private UserRepository userRepository;

    @Autowired
    protected UserFollowServiceImpl(UserFollowRepository repository) {
        super(repository);
        this.followRepository = repository;
    }

    @Override
    @Transactional
    public boolean followToggle(UserPO userPO, Long follow) {
        UserFollowPO po = followRepository.findByUserPO_UserIdAndFollow_UserId(userPO.getUserId(), follow);

        if (po == null) {
            po = new UserFollowPO();
            po.setUserPO(userPO);
            po.setFollow(new UserPO(follow));
            save(po);

            userRepository.updateFansCount(follow, 1);

            return true;
        } else {
            delete(po.getId());

            userRepository.updateFansCount(follow, -1);

            return false;
        }
    }

    @Override
    public Page<UserFollowPO> followers(Long userId, int pageIndex, int pageSize) {
        return followRepository.findByFollow_UserId(userId, PageRequest.of(pageIndex - 1, pageSize));
    }

    @Override
    public long followerCount(Long userId) {
        return followRepository.countByFollow_UserId(userId);
    }

    @Override
    public Page<UserFollowPO> follow(Long userId, int pageIndex, int pageSize) {
        return followRepository.findByUserPO_UserId(userId, PageRequest.of(pageIndex - 1, pageSize));
    }

    @Override
    public long followCount(Long userId) {
        return followRepository.countByUserPO_UserId(userId);
    }

    @Override
    public boolean isFollowed(Long userId, Long follow) {
        return followRepository.existsByUserPO_UserIdAndFollow_UserId(userId, follow);
    }

    @Override
    public UserFollowPO save(BaseSaveDTO saveDTO) {
        return null;
    }
}
